//
//  OAuth.swift
//  Weibo
//
//  Created by Holfioo on 15/9/2.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit
import SVProgressHUD
// OAuth授权信息
class OAuth: UIViewController, UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
        // 加载界面
        webView.loadRequest(NSURLRequest(URL: DHRequestTool.shareTool.OAuthUrl))
    }
    override func loadView() {
        // 给view赋值
        view = webView
        // 设置代理
        webView.delegate = self
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeModal")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoWrite")
    }
    @objc private func closeModal() {
        // 注意再每次关闭的时候也要实现 svpregress动画的关闭
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoWrite() {
        let js = "document.getElementById('userId').value = '105108207@qq.com';" +
        "document.getElementById('passwd').value = '1230456';"
        // 执行 js 脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //MARK: - 代理方法，检测跳转的时候的动作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let requeString = request.URL!.absoluteString // 获得所有的字符串：网页
        if !requeString.hasPrefix(DHRequestTool.shareTool.redirectUri) {
            return true
        }
        
        // 获取字符串
        if let query = request.URL!.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            DHUserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                    //
                    printLog("登录完成")
                    SVProgressHUD.dismiss()
                    // 由于是同一个线程中执行方法。所以。会造成。不能销毁的情况出现很多图层
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(DHSwitchRootViewController, object: "新客户登陆")
                    })
                    
            })
        }else{
            printLog("取消")
        }

        return false
    }
    // 由于无智能提示。重写一个方法
    private func showUsers(account: DHUserAccount) {
        // 从account获得用户的响应信息
            }
    
    
    //MARK: - 代理方法实现动画SVPregressHUD方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
